package com.example.weathernow;

import java.net.URL;
import java.net.URLConnection;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.os.AsyncTask;

class myAsyncTask extends AsyncTask<Void, Void, Void> {
	NodeList nodes;
	URL url;
	URLConnection conn;
	Document doc, doc1;
	DocumentBuilderFactory factory;
	DocumentBuilder builder;
	String woeid = "";

	String cityName = "";
	String CountryName = "";
	String conditonText = "";
	double temp;

	myAsyncTask(double lat, double lon) {
		try {
			System.out.println("O1");
			url = new URL(
					"http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.placefinder%20where%20text='"
							+ lat + "," + lon + "'%20and%20gflags='R'");
			conn = url.openConnection();

			System.out.println("O2");

			factory = DocumentBuilderFactory.newInstance();
			System.out.println("02.1");
			builder = factory.newDocumentBuilder();
			System.out.println("02.2");
			doc = builder.parse(conn.getInputStream());
			System.out.println("02.3");
			nodes = doc.getElementsByTagName("woeid");

			System.out.println("03");

			Element element = (Element) nodes.item(0);
			woeid = getCharacterDataFromElement(element);

			url = new URL("http://weather.yahooapis.com/forecastrss?w=" + woeid + "&u=c");
			
			conn = url.openConnection();
			factory = DocumentBuilderFactory.newInstance();
			builder = factory.newDocumentBuilder();
			doc = builder.parse(conn.getInputStream());
			nodes = doc.getElementsByTagName("yweather:location");
			element = (Element) nodes.item(0);
			cityName = element.getAttribute("city").toString();
			CountryName = element.getAttribute("country").toString();

			nodes = doc.getElementsByTagName("yweather:location");
			element = (Element) nodes.item(0);
			cityName = element.getAttribute("city").toString();
			CountryName = element.getAttribute("country").toString();

			nodes = doc.getElementsByTagName("yweather:condition");
			element = (Element) nodes.item(0);
			conditonText = element.getAttribute("text");
			temp = Integer.parseInt(element.getAttribute("temp"));
			System.out.println(temp);
			
		} catch (Exception e) {
			System.out.println("error");
			System.out.println("XML Pasing Excpetion = " + e);
		}
	}

	@Override
	protected Void doInBackground(Void... params) {
		System.out.println("background");
		return null;
	}

	public String getCharacterDataFromElement(Element e) {
		Node child = e.getFirstChild();
		if (child instanceof CharacterData) {
			CharacterData cd = (CharacterData) child;
			return cd.getData();
		}
		return "";
	}
}